package com.smproject.config.datasorce;

import cn.hutool.core.date.DateUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 动态切换数据库
 * @author hu.liang
 * @Date 2019/6/27 0027
 */
@Aspect
@Component
public class DataSourceAspect {

    private static Logger logger = LoggerFactory.getLogger(DataSourceAspect.class);

    /**
     * 定义
     */
    @Pointcut("within(com.smproject.service.impl..*)") //execution( * com.jht.dlk.*.service.impl.*.*(..)) &&
    public void anyMethod(){}//定义一个切入点

    @Pointcut("execution(* com.smproject.mapper..*.*(..))")  //execution(* com.jht.dlk.repository.dao..*.*(..))
    public void anyDaoMethod(){}

    @Around("anyMethod()||anyDaoMethod()")
    public Object dataSourceChange(ProceedingJoinPoint joinPoint) throws Throwable {
        logger.info("进入该方法");
        String method = joinPoint.getSignature().getName();
        if (method.startsWith("add")
                || method.startsWith("create")
                || method.startsWith("save")
                || method.startsWith("edit")
                || method.startsWith("update")
                || method.startsWith("del")
                || method.startsWith("insert")
                || method.startsWith("delete")
                || method.startsWith("remove")) {
            logger.info("当前时间：{},方法 {}切换至写库", DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"), method);
            DataSourceContextHolder.master();
        } else {
            DataSourceContextHolder.slave();
            logger.info("当前时间：{},方法{}切换至读库", DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"), method);
        }
        try {
            return joinPoint.proceed();
        } finally {
            DataSourceContextHolder.clearDataSource();
            logger.debug("clean datasource");
        }
    }

}
